﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Infrastructure.Data;
using Keepo.Models;
using Keepo.Models.Services;
using AlbumDesigner.Models.ViewModels;
using System.IO;
using Keepo.Helpers;
using AlbumDesigner.Models.Enums;

namespace AlbumDesigner.Controllers
{
    public class DesignerController : Controller
    {
        AlbumContext db = new AlbumContext();

        public ActionResult Index(
            int? albumId,
            int? albumSectionId,
            int? premadePageId,
            int? designerVersion,
            string designerAction = "Design",
            bool login = false)
        {
            var isAdminUser = false;
            var isPreview = designerAction == "Preview";
            var isRender = designerAction == "Render";

            var serverIp = Request.ServerVariables["LOCAL_ADDR"];
            var clientIp = Request.ServerVariables["REMOTE_ADDR"];

            //if this is Render proccess and the request came from the Server
            if (isRender && serverIp == clientIp)
            {
                var renderUser = CreateOrGetRenderUser();

                //login as render user
                UserHelper.Login(new LoginData() { Email = renderUser.Email, Password = renderUser.Password, RememberMe = true }, Response, Session);
            }

            // if localhost then login
            if (login && Request.Url.ToString().Contains("localhost"))
            {
                 UserHelper.Login(new LoginData() { Email = "e.aharoni@gmail.com", Password = "12345", RememberMe = true }, Response, Session);
            }

            var user = UserHelper.CurrentUser();

            //if login
            if (user != null)
            {
                //check if the login user is Admin/Studio/Sales/Photographer
                if (user.UserPermissionId != (int)AlbumUsers.Client)
                {
                    isAdminUser = true;
                }
            }
            //if not login
            else if (!Request.Url.ToString().Contains("localhost"))
            {
                ViewBag.MessageText = "יש להתחבר למערכת.";
                return View("NoPermission");
            }

            //check if there is AlbumId or AlbumSectionId
            if (albumId == null && albumSectionId == null && premadePageId == null)
            {
                ViewBag.MessageText = "יש לבחור אלבום או מקטע ספציפי לעיצוב.";
                return View("NoPermission");
            }

            //check if the user can edit this album/albumSection
            /*if (!AlbumsLogic.canUserEdit(albumId != null ? albumId.Value : -1, albumSectionId != null ? albumSectionId.Value : -1))
            {
                ViewBag.MessageText = "אין לך הרשאה כעורך של האלבום/המקטע המבוקש.";
                return View("NoPermission");
            }*/

            var viewModel = new DesignerData();

            viewModel.AlbumId = albumId;
            viewModel.AlbumSectionId = albumSectionId;
            viewModel.PremadePageId = premadePageId;
            viewModel.DesignerAction = designerAction;
            viewModel.DesignerVersion = designerVersion ?? 1;

            viewModel.ReturnUrl = Request.UrlReferrer != null ? Request.UrlReferrer.ToString() : "";

            //check if the specified album is valid
            if (albumId != null)
            {
                var album = db.Albums.Find(albumId);

                //album not exist
                if (album == null)
                {
                    ViewBag.MessageText = "אלבום זה אינו קיים.";
                    return View("NoPermission");
                }
                //album is locked
                else if (album.AlbumLockStatusId == 1 && !isAdminUser && !isPreview)
                {
                    ViewBag.MessageText = "אלבום זה נעול ולא ניתן לעריכה בשלב זה.";
                    return View("NoPermission");
                }
            }

            //check if the specified album section is valid
            if (albumSectionId != null)
            {
                var albumSection = db.AlbumSections.Find(albumSectionId);

                //section not exist
                if (albumSection == null)
                {
                    ViewBag.MessageText = "מקטע זה אינו קיים.";
                    return View("NoPermission");
                }
                //section is locked
                else if (albumSection.AlbumSectionLockStatusId != 3 && !isAdminUser && !isPreview)
                {
                    ViewBag.MessageText = "מקטע זה נעול ולא ניתן לעריכה בשלב זה.";
                    return View("NoPermission");
                }
            }

            return View(viewModel);
        }

        private User CreateOrGetRenderUser()
        {
            var renderUser = db.Users.FirstOrDefault(m => m.Username == "RenderUser");
            if (renderUser == null)
            {
                var newRenderUser = new User();
                newRenderUser.Username = "RenderUser";
                newRenderUser.Password = Guid.NewGuid().ToString();
                newRenderUser.Email = Guid.NewGuid().ToString();
                newRenderUser.UserPermissionId = (int)AlbumUsers.Admin;
                newRenderUser.Activate = true;
                newRenderUser.RegistrationDate = DateTime.Now;

                db.Users.Add(newRenderUser);
                db.SaveChanges();

                renderUser = newRenderUser;
            }

            return renderUser;
        }
    }
}
